from fastapi import HTTPException

from src.database.models import Region_type
from src.region_service.schemas import (
    Full_regionType_schema,
    Upload_regionType_form
)

from src.database.my_crud import My_crud

from src.user_service.service.auth import raise_401_error

retgion_type_crud = My_crud(Region_type)


class regionType_service:

    async def create_regionType(
        self,
        payload: Upload_regionType_form,
        user_id: int
    ):
        await raise_401_error(user_id)
        if await retgion_type_crud.exist([Region_type.type == payload.type]):
            raise HTTPException(
                status_code=409,
                detail="this regionType exists"
            )

        return await retgion_type_crud.create(
            payload,
            Output_model=Full_regionType_schema
        )

    async def get_regionType(self, type_id: int, user_id: int):
        await raise_401_error(user_id)

        if not await retgion_type_crud.exist([Region_type.id == type_id]):
            raise HTTPException(
                status_code=404,
                detail="this regionType not found"
            )
        return await retgion_type_crud.get(
            [Region_type.id == type_id],
            Full_regionType_schema
        )

    async def edit_regionType(
        self,
        type_id: int,
        payload: Full_regionType_schema,
        user_id: int
    ):
        await raise_401_error(user_id)

        if not await retgion_type_crud.exist([Region_type.id == type_id]):
            raise HTTPException(
                status_code=404,
                detail="this regionType not found"
            )

        if await retgion_type_crud.exist([Region_type.type == payload.type]):
            raise HTTPException(
                status_code=409,
                detail="this regionType has already created"
            )

        return await retgion_type_crud.patch(
            [Region_type.id == type_id],
            new_data=dict(type=payload.type),
            Output_model=Full_regionType_schema
        )

    async def delete_regionType(self, type_id: int, user_id: int):
        await raise_401_error(user_id)

        if not await retgion_type_crud.exist([Region_type.id == type_id]):
            raise HTTPException(
                status_code=404,
                detail="this regionType not found"
            )

        return await retgion_type_crud.remove([Region_type.id == type_id])
